<template>
    <el-dialog
        v-model="dialogVisible"
        @close="closeDialog"
        title="修改分发量"
        :close-on-click-modal="false"
        width="fit-content"
    >
        <el-table :data="times" max-height="300" align="center" border class="mb5">
            <el-table-column :label="`${isTimes ? '分发时段' : '持续分发时间'}`" width="260" header-align="center">
                <template #default="{ row }">
                    <p text-c>
                        <span>{{ row.start_at }}</span>
                        <span v-if="row.end_at">至{{ row.end_at }}</span>
                    </p>
                </template>
            </el-table-column>
            <el-table-column label="剩余分发量" width="100" header-align="center">
                <template #default="{ row }">
                    <p text-c>{{ row.left_num }}</p>
                </template>
            </el-table-column>
            <el-table-column label="修改剩余分发量" width="120" header-align="center">
                <template #default="{ row }">
                    <div class="ph5 pv3">
                        <GInputNumber type="integer" :disabled="row.disabled" v-model="row.editLeftNum"/>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <el-text type="danger">*处于发放中的时段，剩余发放量不可减少；未开始的时段发放量需要大于0</el-text>
        <template #footer>
            <el-button @click="cancelDialog">取消</el-button>
            <el-button type="primary" :loading="btnLoading" :disabled="btnLoading" @click="onDialog">确认</el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
    import { computed, PropType, ref, watch } from "vue";
    import { ElMessage } from "element-plus";
    import { getDateParse } from "@/utils/time";
    import { putRestfulMallCouponIncrease } from "@/assets/api";

    const emit = defineEmits(['update:modelValue', 'change']);
    const props = defineProps({
        modelValue: {
            type: Boolean,
            default: false,
        },
        detail: {
            type: Object as PropType<ObjValueAny>,
            default: () => {
                return {}
            },
        },
    });
    const times = ref<ObjValueAny[]>([]);
    const isTimes = computed(() => {
        return props.detail.times && props.detail.times.length;
    })
    const getTimes = () => {
        const { detail } = props;
        const nowParse = getDateParse();
        if (isTimes.value) {
            for (let row of detail.times) {
                const _leftNum = row.left_num || row.num;
                row.left_num = _leftNum;
                row.editLeftNum = _leftNum;
                const startAt = row.start_at.slice(0, 16);
                const startEnd = row.end_at.slice(0, 16);
                row.disStart = nowParse >= getDateParse(startAt);// 时段 已开始
                row.disabled = nowParse >= getDateParse(startEnd);// 时段 已结束
            }
            times.value = detail.times;
        } else {
            const _leftNum = detail.left_num || detail.num;
            times.value = [{
                start_at: detail.timing_published_at.slice(0, 16),
                end_at: detail.timing_unpublished_at.slice(0, 16),
                left_num: _leftNum,
                editLeftNum: _leftNum,
                num: detail.num,
                disStart: true,
            }]
        }
    }

    let dialogVisible = ref<boolean>(false);// 显示弹窗
    watch(() => props.modelValue, async (newVal: boolean) => {
        dialogVisible.value = newVal;
        if (newVal) {
            btnLoading.value = false;
            getTimes();
        }
    });
    const btnLoading = ref<boolean>(false);
    const onDialog = () => {
        ElMessage.closeAll();
        const storeTimes: ObjValueAny[] = JSON.parse(JSON.stringify(times.value))
        const _times: ObjValueAny[] = [];
        for (let row of storeTimes) {
            if (row.editLeftNum !== 0 && !row.editLeftNum) {
                ElMessage.error('请输入剩余分发量');
                return;
            }
            if (row.editLeftNum <= 0) {
                ElMessage.error('剩余分发量需大于0');
                return;
            }
            if (row.disStart) {
                if (+row.editLeftNum < +row.left_num) {
                    ElMessage.warning('处于发放中状态的时段不可减少发放量');
                    return;
                }
            }
            if (!row.disabled) {
                const difference: number = +row.editLeftNum - +row.left_num;
                row.left_num = +row.editLeftNum;
                row.num = +row.num + difference;
            }
            const _value: ObjValueAny = {
                start_at: row.start_at,
                end_at: row.end_at,
                num: row.num,
            };
            if (row.disStart) {
                _value.left_num = row.editLeftNum;
            }
            _times.push(_value)
        }

        let data: ObjValueAny;
        if (isTimes.value) {
            data = {
                times: _times
            }
        } else {
            data = {
                num: _times[0].num
            }
        }
        ElMessage({
            showClose: true,
            message: `更新中...`,
            type: 'success',
            duration: 0,
        });
        btnLoading.value = true;
        putRestfulMallCouponIncrease(props.detail.id, data).then((resp: ObjValueAny) => {
            ElMessage.closeAll();
            if (resp.code === 200) {
                emit('change');
                ElMessage.success(`更新成功`);
                cancelDialog();
            } else {
                btnLoading.value = false;
                ElMessage.error(resp.msg);
            }
        }).catch(() => {
            ElMessage.error('更新失败');
            btnLoading.value = false;
        })
    }
    // 关闭弹窗
    const cancelDialog = () => {
        dialogVisible.value = false;
    }
    const closeDialog = () => {
        cancelDialog();
        emit('update:modelValue', dialogVisible.value)
    }
</script>